#!/usr/bin/python
# -*- coding:utf-8 -*-
import json
import arrow
from bson import ObjectId
from django import forms
from rest_framework.response import Response
from mongoengine.errors import DoesNotExist
from apps.account_manager.models import (
    UserGroups,
    Modules,
    Permissions
)
from utilities.meta_view import APIViewCreate, APIViewList, APIViewUpdate, APIViewDestroy


class AddUserGroupForm(forms.Form):
    group = forms.CharField(max_length=100, required=False)
    desc = forms.CharField(max_length=100, required=False)
    modules = forms.CharField(required=False)
    user_group_id = forms.CharField(required=False)


class GetUserGroupForm(forms.Form):
    page = forms.IntegerField(required=False)
    pageSize = forms.IntegerField(required=False)
    userGroupId = forms.CharField(required=False)


class ListUserGroupView(APIViewList):
    def get(self, request, *args, **kwargs):
        query = GetUserGroupForm(self.request.GET)
        if not query.is_valid():
            return Response({"status": "failed", "msg": "参数错误"})
        page = query.cleaned_data.get("page") or 1
        page_size = query.cleaned_data.get("pageSize") or 10
        user_group_id = query.cleaned_data.get("userGroupId")
        query = {}
        if user_group_id:
            query = {"user_group_id": user_group_id}
        user_groups = UserGroups.objects.filter(**query).order_by("-created_at").skip((page - 1) * page_size).limit(page_size)
        total = UserGroups.objects.count()
        user_group_list = []
        for user_group in user_groups:
            modules = getattr(user_group, "modules", [])
            if modules:
                modules = [{"id": str(module.id), "module_name": module.module_name} for module in modules]
            user_group_list.append({
                "user_group_id": user_group.user_group_id,
                "group": user_group.group,
                "desc": getattr(user_group, "desc", ""),
                "modules": modules,
                "created_at": arrow.get(user_group.created_at).format("YYYY-MM-DD HH:mm:ss"),
                "updated_at": arrow.get(user_group.updated_at).format("YYYY-MM-DD HH:mm:ss")
            })
        data = {
            "count": total,
            "page": page,
            "data": user_group_list
        }
        return Response(data={"status": "success", "data": data})


class AddUserGroupView(APIViewCreate):
    def post(self, request, *args, **kwargs):
        post_data = self.request.data
        form = AddUserGroupForm(post_data)
        if not form.is_valid():
            return Response({"status": "failed", "msg": "参数错误"})
        group = form.cleaned_data.get("group")
        desc = form.cleaned_data.get("desc")
        try:
            module_ids_str = form.cleaned_data.get("modules") or '[]'
            module_ids = json.loads(module_ids_str.replace("'", "\""))
        except json.JSONDecodeError:
            return Response({"status": "failed", "msg": "参数错误"})
        if not group or not desc or not module_ids:
            return Response({"status": "failed", "msg": "参数错误"})
        try:
            UserGroups.objects.get(group=group)
            return Response({"status": "failed", "msg": "角色已存在"})
        except DoesNotExist:
            pass
        modules = Modules.objects.filter(id__in=[ObjectId(module_id) for module_id in module_ids])
        if not modules:
            return Response({"status": "failed", "msg": "模块不存在"})
        permissions = Permissions.objects.all()
        user_group = UserGroups(group=group, desc=desc, permissions=permissions, modules=modules)
        user_group.save()
        return Response({"status": "success", "msg": "添加角色成功"})


class EditUserGroupView(APIViewUpdate):
    def put(self, request, *args, **kwargs):
        post_data = self.request.data
        form = AddUserGroupForm(post_data)
        if not form.is_valid():
            return Response({"status": "failed", "msg": "参数错误"})
        user_group_id = form.cleaned_data.get("user_group_id")
        desc = form.cleaned_data.get("desc")
        try:
            module_ids_str = form.cleaned_data.get("modules") or '[]'
            module_ids = json.loads(module_ids_str.replace("'", "\""))
        except json.JSONDecodeError:
            return Response({"status": "failed", "msg": "参数错误"})
        if not user_group_id or not desc or not module_ids:
            return Response({"status": "failed", "msg": "参数错误"})
        modules = Modules.objects.filter(id__in=module_ids)
        if not modules:
            return Response({"status": "failed", "msg": "模块不存在"})
        try:
            user_group = UserGroups.objects.get(user_group_id=user_group_id)
        except DoesNotExist:
            return Response({"status": "failed", "msg": "角色不存在"})
        if desc:
            user_group.desc = desc
        if modules:
            user_group.modules = modules
        user_group.save()
        return Response({"status": "success", "msg": "编辑角色成功"})


class DeleteUserGroupView(APIViewDestroy):
    def delete(self, request, *args, **kwargs):
        user_group_ids = self.request.data.get("user_group_ids")
        user_groups = UserGroups.objects.filter(user_group_id__in=user_group_ids)
        for user_group in user_groups:
            if user_group.group in ["api", "审计员", "操作员", "管理员"]:
                return Response({"status": "failed", "msg": "不能删除系统角色"})
        if not user_groups:
            return Response({"status": "failed", "msg": "角色不存在"})
        user_groups.delete()
        return Response({"status": "success", "msg": "删除角色成功"})


class ModuleView(APIViewList):
    def get(self, request, *args, **kwargs):
        module_permissions = Modules.objects.filter().order_by("-created_at")
        permissions = []
        for module_permission in module_permissions:
            permissions.append({
                "id": str(module_permission.id),
                "permission": module_permission.module_name
            })
        data = {
            "data": permissions
        }
        return Response(data={"status": "success", "errcode": 0, "data": data})
